home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: GoTo equivalent in C ??
- Date: 13 Jan 1996 18:05:58 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4d8sa6$mqc@news.iag.net>
- References: <4d67vm$e5h@masala.cc.uh.edu>
- NNTP-Posting-Host: pm2-orl20.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <4d67vm$e5h@masala.cc.uh.edu>, sukku@menudo.uh.edu says...
- >
- >Hi,
- > I have always thought about this. How do you get the effect of goto
- >in C without using "goto"?? For ex, if I have to check for an error in my
- >function for every computation I do, and then do some cleaning up, how do
- >I do it. Here is an example:
- >
- >f()
- >{
- >
- >char *s = (char *) malloc(10 * sizeof(char));
- >int i;
- >
- >i = scanf("%s", s);
- >
- >if(i != 1) /* I wish I could do a goto to the last two lines of the
- function*/
- >{
- > free(s);
- > return;
- >}
- >
- >i = atoi(s);
- >if(i==0)
- >{
- > free(s);
- > return;
- >
- >}
- >free(s);
- >return;
- >
- >}
-
- f()
- {
- int i;
- char *s = malloc(10 * sizeof(char));
-
- if( s != NULL) /* allocation succeeeded */
- {
- if( (scanf("%s", s)) == 1) /* 1 field input */
- {
- if( (i = atoi(s)) != 0) /* converted to non-zero integer */
- {
- /* more code */
- }
- }
- free(s);
- }
- return;
- }
-
- or
-
- f()
- {
- int i;
- char *s = malloc(10 * sizeof(char));
-
- if( s != NULL) /* successful allocation */
- {
- if( ((scanf("%s", s)) == 1)) && ((i = atoi(s)) != 0) ) /* valid input */
- {
- /* more code */
- }
- free(s);
- }
- return;
- }
-
- Note: The && operator guarantees that the scanf test must succeed _before_
- the atoi can be called.
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-